<?php
// +----------------------------------------------------------------------
// | Powered By ThinkPHP 5.0.12
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.bojuwang.net All rights reserved.
// +----------------------------------------------------------------------
// | Date：2018-1
// +----------------------------------------------------------------------
// | Author: ZhengLuwei <512711380@qq.com>
// +----------------------------------------------------------------------
namespace app\bjwlmanager\controller;
use think\Config;
use \think\Db;
use \think\Controller;
use \think\Request;
class System extends ManagerBasic
{
    public function getTree($data){
        $ret=$this->reSort($data);
    	return $ret;
    }
    public function reSort($data,$parent_id=0,$class_layer=0){
    	static $ret = array();
    	foreach ($data as $k => $v){
    		if($v['parent_id']==$parent_id){
    			$v['class_layer'] = $class_layer;
    			$ret[] = $v;
    			$this->reSort($data,$v['id'],$class_layer+1);
    		}
    	}
    	return $ret;
    } 


    /**
     * 加载频道信息列表
     */
    public function channel()
    {
        $list=Db::name('sys_channel')->order('id desc')->paginate(15,false,['query'=>request()->param()]);
        $this->assign('list',$list);
        unset($list);
        return view();
    }
    /**
     * 渲染添加频道的页面
     */
    public function channelAdd()
    {
        return view();
    }
    /**
     * 渲染编辑频道的页面
     */
    public function channelEdit()
    {
        $id=input('get.id');
        $info=Db::name('sys_channel')->where('id',$id)->find();
        $this->assign('info',$info);
        return view();
    }
    /**
     * 添加新的频道信息
     */
    public function channelAddSave()
    {
        $callindex=input('post.callindex');
        $title=input('post.title');
        $sort=input('post.sort');
        $description=input('post.description');
        $info=array();
        $info['call_index']=$callindex;
        $info['title']=$title;
        $info['sort']=$sort;
        $info['description']=$description;
        
        $result=Db::name('sys_channel')->insertGetId($info);
        unset($info);
        if($result>0)
        {
           json_msg(0,'添加成功');
        }
        else{
           json_msg(1,'添加失败');
        }
    }
    /**
     * 编辑保存频道信息
     */
    public function channelEditSave()
    {
        $id=input('post.channel_id');
        $callindex=input('post.call_index');
        $title=input('post.title');
        $description=input('post.description');
        $sort=input('post.sort');
        $info=array();
        $info['call_index']=$callindex;
        $info['title']=$title;
        $info['description']=$description;
        $info['sort']=$sort;
        
        $result=Db::name('sys_channel')->where('id',$id)->update($info);
        unset($info);
        if($result==0)
        {
           json_msg(0,'您没有修改任何资料哦');
        }
        else{
           json_msg(0,'更新成功');
        }
        
    }
    /**
     * 加载分类信息列表
     */
    public function category()
    {
        $list=Db::name('sys_category')->order('id desc')->select();
        $list=$this->getTree($list);
        foreach($list as $k=>$v)
        {
            if($v['parent_id']!=0)
            {
                $list[$k]['title']=str_repeat('&nbsp;',$v['class_layer']*4).'|—&nbsp;'.$v['title'];
            }
            $channelModel=get_channel_model($v['channel_id']);
            $list[$k]['channel_title']=$channelModel['title'];
            unset($channelModel);
        }
        $this->assign('list',$list);
        unset($list);
        return view();
    }
    /**
     * 渲染添加频道的页面
     */
    public function categoryAdd()
    {
        
        $channelList=Db::name('sys_channel')->order('id desc')->select();
        $this->assign('channelList',$channelList);
        unset($channelList);
        $categoryList=Db::name('sys_category')->order('id desc')->select();
        $categoryList=$this->getTree($categoryList);
        foreach($categoryList as $k=>$v)
        {
            if($v['parent_id']!=0)
            {
                $categoryList[$k]['title']=str_repeat('&nbsp;',$v['class_layer']*4).'|—&nbsp;'.$v['title'];
            }
        }
        $this->assign('categoryList',$categoryList);
        unset($categoryList);
        return view();
    }
    /**
     * 添加新的分类信息
     */
    public function categoryAddSave()
    {
        $callindex=input('post.call_index');
        $title=input('post.title');
        $sort=input('post.sort');
        $description=input('post.description');
        $parentId=input('post.parent_id');
        $channelId=input('post.channel_id');
        $imgUrl=input('post.img_url');
        $info=array();
        $info['call_index']=$callindex;
        $info['title']=$title;
        $info['sort']=$sort;
        $info['description']=$description;
        $info['parent_id']=$parentId;
        $info['channel_id']=$channelId;
        $info['img_url']=$imgUrl;
        
        $getId=Db::name('sys_category')->insertGetId($info);
        unset($info);
        if($getId>0)
        {
            $model=get_category_model($getId);
            
            if($model['parent_id']>0)
            {
                $pmodel=get_category_model($model['parent_id']);
                $classLayer=$pmodel['class_layer']+1;
                $classList=$pmodel['class_list'].$getId.',';
                unset($pmodel);
            }
            else
            {
                $classLayer=1;
                $classList=','.$getId.',';
            }
            Db::name('sys_category')->where('id',$getId)->update(['class_list'=>$classList,'class_layer'=>$classLayer]);
            json_msg(0,'添加成功');
        }
        else{
           json_msg(1,'添加失败');
        }
    }
    /**
     * 渲染编辑分类的页面
     */
    public function categoryEdit()
    {
        $id=input('get.id');
        $info=Db::name('sys_category')->where('id',$id)->find();
        $this->assign('info',$info);
        $categoryList=Db::name('sys_category')->order('id desc')->select();
        $categoryList=$this->getTree($categoryList);
        foreach($categoryList as $k=>$v)
        {
            if($v['parent_id']!=0)
            {
                $categoryList[$k]['title']=str_repeat('&nbsp;',$v['class_layer']*4).'|—&nbsp;'.$v['title'];
            }
        }
        $this->assign('categoryList',$categoryList);
        unset($categoryList);
        return view();
    }
    /**
     * 保存编辑的分类信息
     */
    public function categoryEditSave()
    {
        $id=input('post.category_id');
        $callindex=input('post.call_index');
        $title=input('post.title');
        $sort=input('post.sort');
        $description=input('post.description');
        $parentId=input('post.parent_id');
        $imgUrl=input('post.img_url');
        $info=array();
        $info['call_index']=$callindex;
        $info['title']=$title;
        $info['sort']=$sort;
        $info['description']=$description;
        $info['img_url']=$imgUrl;
        //判断选择的父级ID是不是自己，如果使自己则不更新，否则会造成死循环
        if($id!=$parentId)
        {
            $info['parent_id']=$parentId;
        }
        
        $result=Db::name('sys_category')->where('id',$id)->update($info);
        unset($info);
        if($result>0)
        {
            $model=get_category_model($id);
            
            if($model['parent_id']>0)
            {
                $pmodel=get_category_model($model['parent_id']);
                $classLayer=$pmodel['class_layer']+1;
                $classList=$pmodel['class_list'].$id.',';
                unset($pmodel);
            }
            else
            {
                $classLayer=1;
                $classList=','.$id.',';
            }
            Db::name('sys_category')->where('id',$id)->update(['class_list'=>$classList,'class_layer'=>$classLayer]);
            json_msg(0,'修改成功');
        }
        else{
           json_msg(1,'修改失败');
        }
    }
    /**
     * 删除指定的分类信息
     */
    public function categoryDel()
    {
        $id=input('post.id');
        if(!isset($id))
        {
           json_msg(1,'请求参数错误');
        }
        $result=Db::name('sys_category')->where('class_list','like','%,'.$id.',%')->delete();
        if($result==0)
        {
           json_msg(0,'没有删除任何数据');
        }
        else
        {
           json_msg(0,'删除成功');
        }
        json_msg(1,'请求失败');
    }
    /**
     * 加载广告信息列表
     */
    public function ad()
    {

        $categoryId = input('param.category_id');
        $keywords = input('param.keywords');
        $where=[];
        $categoryId ? $where['category_id']=$categoryId :'';
        $keywords ? $where['title'] = ['like',"%{$keywords}%"]:'';
        $list=Db::name('sys_ad')->where($where)->order('id desc')->paginate(15,false,['query'=>request()->param()])->each(function($item, $key){
            $item['typeshow']=config('ad_type_arr')[$item['type']];
            $categoryModel=get_category_model($item['category_id']);
            $item['category_title']=$categoryModel['title'];
            return $item;
        });

        $this->assign('list',$list);
        unset($list);
        $category = Db::name('sys_category')->where('channel_id',3)->select();
        $this->assign('category',$category);
        return view();
    }
    /**
     * 渲染添加广告的页面
     */
    public function adAdd()
    {
        $categoryList=Db::name('sys_category')->where('channel_id',3)->order('id desc')->select();
        $categoryList=$this->getTree($categoryList);
        foreach($categoryList as $k=>$v)
        {
            if($v['parent_id']!=0)
            {
                $categoryList[$k]['title']=str_repeat('&nbsp;',$v['class_layer']*4).'|—&nbsp;'.$v['title'];
            }
        }
        $this->assign('categoryList',$categoryList);
        unset($categoryList);
        return view();
    }
    /**
     * 添加新的广告信息
     */
    public function adAddSave()
    {
        $type=input('post.type');
        $title=input('post.title');
        $sort=input('post.sort');
        $description=input('post.description');
        $categoryId=input('post.category_id');
        $linkUrl=input('post.link_url');
        $xlink_url=input('post.xlink_url');
        $imgUrl=input('post.img_url');
        $info=array();
        $info['number']=date("YmdHis").rand(100,999).'8';
        $info['type']=$type;
        $info['title']=$title;
        $info['sort']=$sort;
        $info['description']=$description;
        $info['category_id']=$categoryId;
        $info['channel_id']=8;
        $info['link_url']=$linkUrl;
        $info['xlink_url']=$xlink_url;
        $info['img_url']=$imgUrl;
        
        $getId=Db::name('sys_ad')->insertGetId($info);
        unset($info);
        if($getId>0)
        {
            json_msg(0,'添加成功');
        }
        else{
           json_msg(1,'添加失败');
        }
    }
    /**
     * 渲染编辑分类的页面
     */
    public function adEdit()
    {
        $id=input('get.id');
        $info=Db::name('sys_ad')->where('id',$id)->find();
        $this->assign('info',$info);
        $categoryList=Db::name('sys_category')->where('channel_id',3)->order('id desc')->select();
        $categoryList=$this->getTree($categoryList);
        foreach($categoryList as $k=>$v)
        {
            if($v['parent_id']!=0)
            {
                $categoryList[$k]['title']=str_repeat('&nbsp;',$v['class_layer']*4).'|—&nbsp;'.$v['title'];
            }
        }
        $this->assign('categoryList',$categoryList);
        unset($categoryList);
        return view();
    }
    //停用
    public function adStop()
    {
        $id = input('post.id');
        if(!isset($id))
        {
            json_msg(1,'请求参数错误');
        }
        $result=Db::name('sys_ad')->where('id',$id)->setField('status',1);
        if($result==0)
        {
            json_msg(0,'状态未更改');
        }
        else
        {
            json_msg(0,'禁用成功');
        }
    }

    //启用
    public function adStart()
    {
        $id=input('post.id');
        if(!isset($id))
        {
            json_msg(1,'请求参数错误');
        }
        $result=Db::name('sys_ad')->where('id',$id)->setField('status',0);
        if($result==0)
        {
            json_msg(0,'状态未更改');
        }
        else
        {
            json_msg(0,'启用成功');
        }
    }
    /**
     * 保存编辑的分类信息
     */
    public function adEditSave()
    {
        
        $id=input('post.ad_id');
        $categoryId=input('post.category_id');
        $title=input('post.title');
        $sort=input('post.sort');
        $description=input('post.description');
        $type=input('post.type');
        $linkUrl=input('post.link_url');
        $xlink_url=input('post.xlink_url');
        $imgUrl=input('post.img_url');
        $info=array();
        $info['category_id']=$categoryId;
        $info['title']=$title;
        $info['sort']=$sort;
        $info['description']=$description;
        $info['type']=$type;
        $info['link_url']=$linkUrl;
        $info['xlink_url']=$xlink_url;
        $info['img_url']=$imgUrl;
        
        $result=Db::name('sys_ad')->where('id',$id)->update($info);
        unset($info);
        if($result>0)
        {
            json_msg(0,'修改成功');
        }
        else{
           json_msg(1,'修改失败');
        }
    }
    /**
     * 删除指定的广告信息
     */
    public function adDel()
    {
        $id=input('post.id');
        if(!isset($id))
        {
           json_msg(1,'请求参数错误');
        }
        $result=Db::name('sys_ad')->where('id',$id)->delete();
        if($result==0)
        {
           json_msg(0,'没有删除任何数据');
        }
        else
        {
           json_msg(0,'删除成功');
        }
        json_msg(1,'请求失败');
    }
    /**
     * 消息列表 (系统消息 业务消息)
     * @return \think\response\View
     */
    public function message(){
        $messageList=Db::name('sys_message')->alias("m")
            ->field("m.*,u.user_name")
            ->join("user u","m.user_id = u.id","left")
            ->order('m.id desc')
            ->paginate(15,false,['query'=>request()->param()]);
        $this->assign("messageList",$messageList);
        unset($messageList);
        return view();
    }
    /**
     * 添加消息 模板信息
     * @return \think\response\View
     */
    public function messageAdd(){
        return view();
    }
    /**
     * 执行添加修改  ajax实现
     */
    public function messageAddSave(){
        if(Request::instance()->isPost() ){
            $data = Request::instance()->post();
            $info["type"]        = $data["type"];
            $info["title"]       = $data["title"];
            $info["content"]     = $data["content"];
            $info["sort"]        = $data["sort"];
            $info["is_read"]     = 0;
            if(input("user")!=0){
                $mobile = input("mobile");
                $mobile = array_filter(explode("|",$mobile));
                $where["mobile"] = array("in",$mobile);
                $user = Db::name("user")->field('id,mobile')->where($where)->select();
                foreach ($user as $k=>$v){
                    $info["user_id"] = $v["id"];
                    $res = Db::name("sys_message")->insertGetId($info);
                }
            }else{
                $user = Db::name("user")->field('id')->select();
                foreach ($user as $v) {
                    $info['user_id'] = $v['id'];
                    $res = Db::name("sys_message")->insertGetId($info);
                }
            }
            unset($user,$userList,$useMobile,$info);
            if($res>0)
            {
                json_msg(0,'添加成功');
            }
            else{
                json_msg(1,'添加失败');
            }
        }
    }
    /**
     * 删除指定的消息信息
     */
    public function MessageDel(){
        $id=input('post.id');
        if(!isset($id))
        {
            json_msg(1,'请求参数错误');
        }
        $result=Db::name('sys_message')->where("id",$id)->delete();
        if($result==0)
        {
            json_msg(0,'没有删除任何数据');
        }
        else
        {
            json_msg(0,'删除成功');
        }
        json_msg(1,'请求失败');
    }
    /*
     * 批量删除消息
     */
    public function messageDeletes(){
        $ids=input('post.ids');
        $result=Db::name('sys_message')->where('id','in',$ids)->delete();
        if($result)
        {
            json_msg(0,'删除成功');
        }
        json_msg(1,'删除失败');
    }
    /**
     * @return \think\response\View
     * 系统配置  修改
     */
    public function config(){
        if (!$this->request->isPost()) {
            $this->assign('title', $this->title);
            return view();
        }
        foreach ($this->request->post() as $key => $vo) {
            sysconf($key, $vo);
        }
        return view();
    }
    /*
     * 快递设置
     * */
    public function express()
    {
        $list = Db::name('sys_express')->paginate(15,false,['query'=>request()->param()]);
        $this->assign('list',$list);
        return $this->fetch();
    }
    /*
     * 添加
     * */
    public function addExpress()
    {
        if (request()->isPost())
        {
            $provinces = input('param.provinces/a');
            $title = input('param.title');
            $money = input('param.money');
            $status = input('param.status');
            $status ? $status : 1 ;
            if ($provinces)
            {
                $provincesCode = '||'.implode('||',$provinces).'||';
                foreach ($provinces as $k=>$v)
                {
                    $arr[] = province($v);
                }
                $provinces= '||'.implode('||',$arr).'||';
            }
            $data = [
                'title' => $title,
                'money'=>$money,
                'status'=> $status,
                'provinces' => $provinces,
                'provinces_code'=>$provincesCode
            ];
            if (Db::name('sys_express')->insert($data))
            {
                json_msg(0,'添加成功');
            } else {
                json_msg(1,'添加失败');
            }
        } else {
            $provinces = Db::name('provinces')->select();
            $this->assign('provinces', $provinces);
            return $this->fetch();
        }
    }
    /*
     * 修改
     * */
    public function editExpress()
    {
        $id = input('param.id');
        if (request()->isPost())
        {
            $provinces = input('param.provinces/a');
            $title = input('param.title');
            $money = input('param.money');
            $status = input('param.status');
            $status ? $status : 1 ;
            $action = input('param.action');
            if (isset($action))
            {
                $data = ['status'=>$status];
            } else {
                if ($provinces)
                {
                    $provincesCode = '||'.implode('||',$provinces).'||';
                    foreach ($provinces as $k=>$v)
                    {
                        $arr[] = province($v);
                    }
                    $provinces= '||'.implode('||',$arr).'||';
                }
                $data = [
                    'title' => $title,
                    'money'=>$money,
                    'status'=> $status,
                    'provinces' => $provinces,
                    'provinces_code'=>$provincesCode
                ];
            }
            if (Db::name('sys_express')->where('id',$id)->update($data))
            {
                json_msg(0,'修改成功');
            } else {
                json_msg(1,'修改失败');
            }
        } else {
            $provinces = Db::name('provinces')->select();
            $this->assign('provinces', $provinces);
            $info = Db::name('sys_express')->find($id);
            $this->assign('info',$info);
            return $this->fetch();
        }
    }
    /*
     * 删除
     * */
    public function delExpress()
    {
        $id = input('param.id');
        if (Db::name('sys_express')->delete($id))
        {
            json_msg(0,'删除成功');
        } else {
            json_msg(1,'删除失败');
        }
    }
    /*奖品设置*/
    public function prize()
    {
        $list = Db::name('prize')->select();
        $this->assign('list',$list);
        return $this->fetch();
    }
    public function editPrize()
    {
        $id = input('param.id');
        if (request()->isPost()) {
            $content = input('param.content');
            $odds = input('param.odds');
            $data = ['content'=>trim($content),'odds'=>$odds];
            $res = Db::name('prize')->where('id',$id)->update($data);
            if ($res || $res == 0) {
                json_msg(0,'修改成功');
            } else {
                json_msg(1,'修改失败');
            }
        } else {
            $info = Db::name('prize')->where('id',$id)->find();
            $this->assign('info',$info);
            return $this->fetch();
        }
    }
 
}